package edu.zut.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "SessionDemo", value = "/session/demo1")
public class SessionDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //session对象的创建   默认会先去服务器找对应的session，找不到就新建一个
        HttpSession session = request.getSession();
        //判断当前服务器中是否有对应的session。有就返回null，如果没有，就创建
//        request.getSession(true);
        //判断当前服务器中是否有对应的session。有就返回，如果没有，就返回null
//        request.getSession(false);
        if (session.isNew()) {
            System.out.println("当前session是新的session");
        }else
            System.out.println("当前session是旧的");
        //获取session的id
        String id = session.getId();
        Cookie cookie = new Cookie("JSESSIONID", id);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        //将session的id进行持久化，间接实现session的持久化
        cookie.setMaxAge(60*60);
        //session的默认销毁时间30分钟，设置其销毁时间
        session.setMaxInactiveInterval(60*60);
        response.addCookie(cookie);
        response.getWriter().write(id);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
